package com.czk.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.constant.WareConstant;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.gulimall.ware.dao.PurchaseDao;
import com.czk.gulimall.ware.entity.PurchaseDetailEntity;
import com.czk.gulimall.ware.entity.PurchaseEntity;
import com.czk.gulimall.ware.service.PurchaseDetailService;
import com.czk.gulimall.ware.service.PurchaseService;
import com.czk.gulimall.ware.service.WareSkuService;
import com.czk.gulimall.ware.vo.MergeVo;
import com.czk.gulimall.ware.vo.PurchaseDoneVo;
import com.czk.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivedPurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                // 新建或为领取的采购单
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mergePurchase(MergeVo mergeVo) {
        // 拿到id
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            // 新建状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            // 拿到id
            purchaseId = purchaseEntity.getId();
        }
        // 确认采购单状态是0或1
        PurchaseEntity entity = this.getById(purchaseId);
        // 没有被领取或分配才能好继续合并
        if (entity.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()||
        entity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(i -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                // 设置采购需求id
                purchaseDetailEntity.setId(i);
                // 设置采购单id
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                // 已分配
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            //
            purchaseDetailService.updateBatchById(collect);

            // 更新采购单信息
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
    }

    @Override
    public void received(List<Long> ids) {
        // 1 确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(item -> {
            PurchaseEntity purchaseEntity = this.getById(item);
            return purchaseEntity;
        })
                .filter(purchaseEntity -> {
                    if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                            purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                })
                .map(item -> {
                    // 2 改变采购单的状态
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());
        this.updateBatchById(collect);

        // 改变采购项
        collect.forEach(item -> {
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(item.getId());
            // 更新状态
            List<PurchaseDetailEntity> collect1 = list.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            // 批量更新
            purchaseDetailService.updateBatchById(collect1);
        });
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 1 改变采购单状态
        Long id = purchaseDoneVo.getId();
        boolean flag=true;

        List<PurchaseDetailEntity> updates=new ArrayList<>();
        // 2 改变采购项状态
        for (PurchaseItemDoneVo item : purchaseDoneVo.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity=new PurchaseDetailEntity();
            // 分离成功的采购项和非成功的采购项
            if (item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag=false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                // 成功
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 成功采购则入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                // 更新仓库
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            purchaseDetailEntity.setId(item.getItemId());
            // 加入
            updates.add(purchaseDetailEntity);
        }
        // 批量更新
        purchaseDetailService.updateBatchById(updates);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        // 修改时间
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }
}